<template>
    <div>
        <div class="search-container" v-show="isShowSearch">
            <el-input v-model="searchItem.userName" placeholder="用户名" style="width: 200px;margin-right: 5px"
                      clearable></el-input>
            <el-button type="primary" @click="onSearch">查询</el-button>
        </div>
        <div class="operator-container">
            <div>
                <el-button type="danger" @click="deletedMany" :disabled="this.multipleSelection.length<=0">删除所选
                </el-button>
                <el-button type="primary" @click="added">添加用户</el-button>
            </div>
            <div>
                <el-tooltip class="item" effect="dark" content="刷新" placement="bottom-start">
                    <el-button type="success" circle plain @click="onRefresh"><i class="el-icon-refresh"></i>
                    </el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="searchCloseOpenText" placement="bottom-start">
                    <el-button type="info" circle plain @click="onOpenOrClose"><i class="el-icon-search"></i>
                    </el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="显隐列" placement="bottom-start">
                    <el-button type="warning" circle plain><i class="el-icon-s-grid"></i></el-button>
                </el-tooltip>
            </div>
        </div>
        <div class="content-container">
            <el-table
                    ref="multipleTable"
                    :data="userList"
                    border
                    v-loading="loading"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        width="40">
                </el-table-column>
                <el-table-column
                        label="用户名"
                        align="center"
                        prop="userName"
                        width="120">
                </el-table-column>
                <el-table-column
                        align="center"
                        width="180"
                        prop="createTime"
                        label="创建时间">
                    <template slot-scope="scope">
                        {{ fmtDataTime(scope.row) }}
                    </template>
                </el-table-column>
                <el-table-column
                        header-align="center"
                        align="center"
                        prop="isDel"
                        width="80"
                        label="是否启用">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.isDel"
                                active-color="#ff4949"
                                inactive-color="#13ce66" @change="isDelChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="userRoles"
                        label="拥有角色">
                    <template slot-scope="scope">
                        <div v-if="scope.row.userRoles.length>0">
                            <el-tag type="success" v-for="(item,index) in scope.row.userRoles" :key="index"
                                    style="margin-right: 5px">
                                {{ item.roleName }}
                            </el-tag>
                        </div>
                        <div v-else>
                            <el-tag type="danger">无角色</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                        header-align="center"
                        align="center"
                        width="180"
                        prop="id"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" @click="onDivided(scope.row)">分配角色</el-button>
                        <el-button type="text" @click="onDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex;justify-content: right;margin-top: 5px">
                <el-pagination
                        :hide-on-single-page="true"
                        background
                        @size-change="pageSizeChange"
                        @current-change="currentPageChange"
                        @prev-click="prevClick"
                        @next-click="nextClick"
                        :current-page.sync="searchItem.pageNumber"
                        :page-sizes="[5,10, 20, 50, 100]"
                        layout="sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>
        </div>
        <div>
            <new-dialog ref="dialog" width="20%" title="添加用户" @onSubmit="onSubmit" @reset="reset">
                <el-form ref="form" :model="userInfo" label-width="80px" :rules="rules">
                    <el-row :gutter="10">
                        <el-col :span="24">
                            <el-form-item label="用户名:" prop="userName">
                                <el-input v-model="userInfo.userName" placeholder="用户名"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="24">
                            <el-form-item label="密 码:" prop="passWord">
                                <el-input v-model="userInfo.passWord" placeholder="密码" show-password></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="24">
                            <el-form-item label="确认密码:" prop="passWord2">
                                <el-input v-model="userInfo.passWord2" placeholder="再次输入密码" show-password></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </new-dialog>
            <new-dialog ref="dialogRoles" width="30%" title="分配角色" @onSubmit="onDividedRolesSubmit" @reset="reset">
                <el-row :gutter="10">
                    <el-col :span="24">当前用户:
                        <el-tag type="success" size="medium">{{ userInfo.userName }}</el-tag>
                        <el-divider></el-divider>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="24">
                        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                            全选
                        </el-checkbox>
                        <div style="margin: 15px 0;"></div>
                        <el-checkbox-group v-model="selectRoles" @change="handleCheckedRolesChange">
                            <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id">
                                {{ role.name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-col>
                </el-row>
            </new-dialog>
        </div>
    </div>
</template>

<script>
import {added, deleted, deletedMany, edited, getAll} from "@/api/user";
import {formatterDateFull, ObjectToString} from "@/network/util"
import {getAll as getRoleAll, setUserRoles} from "@/api/roles"
import NewDialog from "@/components/common/NewDialog";

export default {
    name: "index",
    data() {
        let validatePassWord2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.userInfo.passWord) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            loading: false,
            searchItem: {
                userName: "",
                pageNumber: 1,
                pageSize: 10
            },
            searchCloseOpenText: "关闭查询",
            isShowSearch: true,
            userList: [],
            roleList: [],
            multipleSelection: [],
            userInfo: {
                userName: "",
                passWord: "",
                passWord2: "",
                isDel: false
            },
            rules: {
                userName: [
                    {required: true, message: '请输入用户名', trigger: 'blur'}
                ],
                passWord: [
                    {required: true, message: '请输入密码', trigger: 'blur'}
                ],
                passWord2: [
                    {validator: validatePassWord2, trigger: 'blur'}
                ]
            },
            selectRoles: [],
            isIndeterminate: null,
            checkAll: false,
            total: -1,
            pagination: {
                total: -1,
                pageSize: 10,
                pageCount: -1
            }
        }
    },
    mounted() {
        this.initUserList();
        this.initRoleList();
    },
    components: {
        NewDialog,
    },
    methods: {
        /******************Init******************/
        initUserList() {
            this.loading = true;
            getAll(this.searchItem).then(res => {
                if (res) {
                    this.total = res.data.total;
                    this.userList = res.data.result;
                    this.loading = false;
                    // this.pagination.total = res.data.total;
                    // this.pagination.pageCount = res.data.pageCount;
                    // this.pagination.pageSize = res.data.pageSize;

                }
            })
        },
        initRoleList() {
            getRoleAll(null).then(res => {
                this.roleList = res.data;
            })
        },
        /**************search相关****************/
        onSearch() {
            this.searchItem.pageNumber = 1;
            this.initUserList();
        },
        /**********Operator相关***************/
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        added() {
            this.$refs.dialog.onOpen();
        },
        deletedMany() {
            if (this.multipleSelection.length > 0) {
                this.$confirm("你确定要删除所选用户吗?", "提示信息", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    deletedMany(this.multipleSelection.map(x => x.id).join(",")).then(res => {
                        if (res) {
                            this.$message.success(res.message);
                            this.deleteShowPageEnd(this.multipleSelection.length);
                            this.reset();
                            this.initUserList();
                        }
                    })
                }).catch(() => {
                    this.$message.info("取消删除操作")
                })
            } else {
                this.$message.info("未选中内容")
            }
        },
        onRefresh() {
            this.searchItem = {
                userName: "",
                pageNumber: 1,
                pageSize: 10
            },
                this.reset();
            this.initUserList();
        },
        onOpenOrClose() {
            this.isShowSearch = !this.isShowSearch;
            this.searchCloseOpenText = this.isShowSearch ? "关闭查询" : "打开查询";
        },
        /**********table相关*******************/
        onDel(row) {
            this.$confirm("您确定要删除当前用户吗?", "提示信息", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                deleted(row.id).then(res => {
                    if (res) {
                        this.$message.success(res.message);
                        this.deleteShowPageEnd(1);
                        this.initUserList();
                    }
                })
            }).catch(() => {
                this.$message.info("取消删除操作")
            })

        },
        fmtDataTime(row) {
            return formatterDateFull(row.createTime);
        },
        onDivided(row) {
            Object.assign(this.userInfo, row);
            this.selectRoles = this.userInfo.userRoles.map(x => x.roleId);
            this.$refs.dialogRoles.onOpen();
        },
        onDividedRolesSubmit() {
            this.$message.success("人员分配角色");
            let roleIds = ObjectToString(this.selectRoles);
            setUserRoles(this.userInfo.id, roleIds).then(res => {
                if (res) {
                    this.$refs.dialogRoles.onOpen();
                    this.initUserList();
                    this.$message.success(res.message);
                }
            })
        },
        isDelChange(row) {
            Object.assign(this.userInfo, row);
            edited(this.userInfo).then(res => {
                if (res) {
                    this.$message.success(res.message);
                    this.reset();
                }
            }).catch(error => {
                console.log(error);
            })
        },
        /*********Dialog相关******************/
        onSubmit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    added(this.userInfo).then(res => {
                        if (res) {
                            this.$message.success(res.message);
                            this.initUserList();
                            this.$refs.dialog.onOpen();
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        /*******Dialog Roles相关************/
        handleCheckAllChange(val) {
            this.selectRoles = val ? this.roleList.map(x => x.id) : [];
            this.isIndeterminate = false;
        },
        handleCheckedRolesChange(value) {
            this.selectRoles = value;
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.roleList.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
        },
        /**********pagination相关**********/
        pageSizeChange(size) {
            this.searchItem.pageSize = size;
            this.initUserList();
        },
        currentPageChange(current) {
            this.searchItem.pageNumber = current;
            this.initUserList();
        },
        prevClick(current) {
            this.searchItem.pageNumber = current;
            this.initUserList();
        },
        nextClick(current) {
            this.searchItem.pageNumber = current;
            this.initUserList();
        },
        deleteShowPageEnd(deleteCount) {
            let totalPage = Math.ceil((this.total - deleteCount) / this.searchItem.pageSize);
            let currentPage = this.searchItem.pageNumber > totalPage ? totalPage : this.searchItem.pageNumber;
            this.searchItem.pageNumber = this.searchItem.pageNumber < 1 ? 1 : currentPage;
        },
        /*********重置********************/
        reset() {
            this.userInfo = {
                userName: "",
                passWord: "",
                isDel: false
            },
                this.isIndeterminate = null;
            this.checkAll = false;
            this.selectRoles = [];
        },
    },
}
</script>

<style scoped>

.search-container {
    display: flex;
    justify-content: right;
    margin-bottom: 10px;
}

.operator-container {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

</style>